package com.tedu.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * Author：毕龙
 * Date: 2023/7/22 9:11
 */
public class JDBCUtil {

    private static Properties prop = new Properties();

    static {
        InputStream is = JDBCUtil.class.getClassLoader().getResourceAsStream("com/tedu/conf/jdbc.properties");
        try {
            prop.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    //保证线程的数据是唯一的
    private static ThreadLocal<Connection> tl = new ThreadLocal<>();

    public static Connection getConnection(){
        //获取线程中的conn
        Connection conn = tl.get();

        if(conn == null){
            try {
                Class.forName(prop.getProperty("driver"));

                conn = DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("username"), prop.getProperty("password"));

                //将获取的conn存放在线程
                tl.set(conn);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        return conn;
    }

    public static void release(Connection conn){

        if(conn!=null){
            try {
                conn.close();
                tl.remove();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void release(ResultSet rs, Statement pstm){

        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(pstm!=null){
            try {
                pstm.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }



    }
    public static void release( Statement pstm){



        if(pstm!=null){
            try {
                pstm.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }



    }

}
